<?php

defined('ROOT_PATH') or define('ROOT_PATH', realpath(dirname(__file__) . '/../'));

define('GRAPH_HOST', 'http://namnv.younetco.com/nuo2/graph/');

define('MEDIA_PATH', ROOT_PATH . '/media');

set_include_path(ROOT_PATH . '/include');

//$path = 'photo/ddddscdegvdegdsfasdfasfsadf-w64h100-photo.jpg';
$path = $_GET['path'];

function check($path)
{
	$base = substr($path, strrpos($path, '/') + 1);

	if (false == preg_match("#^(?P<id>\w+)-(?P<option>[a-z0-9]{2,10})-photo\.(gif|jpg|png)$#", $base, $match))
	{
		return 0;
	}

	if (!preg_match_all("#([a-z])([0-9]+)#", $match['option'], $option))
	{
		return 0;
	}

	$option = array_merge(array(
			'w' => null,
			'h' => null,
			'c' => null,
			's' => null
	), array_combine($option[1], $option[2]));

	$id = $match['id'];

	$request = GRAPH_HOST . 'image.php?' . http_build_query(array('id' => $id));

	$file = file_get_contents($request);

	if (empty($file))
	{
		return 0;
	}

	require_once 'WideImage/WideImage.php';

	$image = WideImage::load($file) -> resize($option['w'], $option['h']);

	$image -> saveToFile(MEDIA_PATH . '/' . $path);

	$image -> output('jpg');

	return 1;
}

check($path);
